<?php

declare(strict_types=1);

namespace App\Controller\Admin\System;

use App\Entity\AdminUser;
use App\Entity\Log;
use App\Entity\LogType;
use App\Utils\Annotation\ApiAuthority;
use App\Utils\Annotation\ApiName;
use App\Utils\Annotation\ApiParam;
use App\Utils\Traits\ControllerTrait;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Class LogController
 * @package App\Controller\Admin\System
 * @Route("/admin/system/log", name="admin-system-log-")
 * @ApiName(name="日志")
 */
class LogController extends AbstractController {
    use ControllerTrait;

    /**
     * @ApiName(name="获取日志列表")
     * @ApiParam(name="log_type_id", type="integer", comment="日志类型ID")
     * @ApiParam(name="admin_user", type="string", comment="用户")
     * @ApiParam(name="date", type="array", comment="日期")
     * @ApiParam(name="page", type="integer", comment="页码数", default="1")
     * @ApiParam(name="limit", type="integer", comment="每页条数", default="5")
     * @ApiAuthority(need="admin.system.log")
     * @Route("/list", methods={"GET"}, name="list")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Exception
     */
    public function list (Request $request) {
        $params = $this->onlyDeclare($request);
        $logs_data = $this->getDoctrine()->getRepository(Log::class)->search($params);
        $logs_total = $this->getDoctrine()->getRepository(Log::class)->searchTotal($params);
        $log_types = $this->getDoctrine()->getRepository(LogType::class)->findAllToArray();
        $admin_users = $this->getDoctrine()->getRepository(AdminUser::class)->findAllToArray();
        foreach ($logs_data as &$log) {
            $log['log_type_name'] = $log_types[$log['log_type_id']] ?? '-';
            $log['admin_user_name'] = $admin_users[$log['admin_user_id']] ?? '-';
            $log['created_at'] = $log['created_at']->format('Y-m-d H:i:s');
        }
        return json_success([
            'data'  => $logs_data,
            'total' => $logs_total,
        ]);
    }

    /**
     * @ApiName(name="获取日志类型列表")
     * @ApiAuthority(need="admin.system.log")
     * @Route("/type-list", methods={"GET"}, name="type-list")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     * @throws \Exception
     */
    public function typeList (Request $request) {
        $log_types = $this->getDoctrine()->getRepository(LogType::class)->getArrayResult();
        return json_success([
            'data' => $log_types,
        ]);
    }
}